<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useSgesMAStore } from './MountainGesCalA.ts'
import { storeToRefs } from 'pinia'

// 使用store
const store = useSgesMAStore()
const { displayInfo } = storeToRefs(store)

// 控制面板显示的响应式变量
const isVisible = ref(false)

// 可折叠面板状态
const expandedSections = ref<Record<string, boolean>>({})

// 监听displayInfo变化，控制面板显示/隐藏
watch(() => displayInfo.value, (newInfo) => {
  // console.log('displayInfo changed:', newInfo);

  // 检查对象是否为空
  const isEmpty = !newInfo || Object.keys(newInfo).length === 0;
  // console.log('isEmpty:', isEmpty);

  // 只有当面板显示状态需要改变时才更新isVisible
  if (isEmpty && isVisible.value) {
    isVisible.value = false;
    // console.log('隐藏面板');
  } else if (!isEmpty && !isVisible.value) {
    isVisible.value = true;
    // console.log('显示面板:', newInfo);
  }
}, {
  immediate: true
})

// 关闭面板的函数
const closePanel = () => {
  isVisible.value = false;
  console.log('用户点击关闭按钮，隐藏面板');
}

// 切换可折叠面板
const toggleSection = (title: string) => {
  expandedSections.value[title] = !expandedSections.value[title]
}

// 检查属性是否可编辑
const isEditable = (value: any): boolean => {
  return value && typeof value === 'object' && value.editable === true
}

// 获取属性的值
const getValue = (value: any): any => {
  if (value && typeof value === 'object' && 'value' in value) {
    return value.value
  }
  return value
}

// 获取属性关联的ref名称
const getRefName = (value: any): string => {
  if (value && typeof value === 'object' && 'ref' in value) {
    return value.ref
  }
  return ''
}

// 更新store中的值
const updateValue = (refName: string, value: string) => {
  const numericValue = parseFloat(value);
  const finalValue = isNaN(numericValue) ? value : numericValue;

  if (refName in store && typeof (store as any)[refName] === 'object' && (store as any)[refName].value !== undefined) {
    (store as any)[refName].value = finalValue
  }
}

// 检查值是否为数组（如坐标和旋转）
const isArrayValue = (value: any): boolean => {
  const actualValue = getValue(value)
  return Array.isArray(actualValue);
}

// 格式化数组值显示
const formatArrayValue = (value: any[]): string => {
  if (value.length === 3) {
    return `(${value[0].toFixed(4)}, ${value[1].toFixed(4)}, ${value[2].toFixed(4)})`;
  }
  return value.join(', ');
}
</script>

<template>
  <div v-if="isVisible && displayInfo" class="fixed top-0 left-0 w-full h-full pointer-events-none">
    <div class="absolute top-[100px] right-[20px] w-[350px] bg-gray-800/80 border-2 border-white/90 rounded-lg p-4 shadow-lg z-[1000] text-white font-sans pointer-events-auto">
      <div class="mb-4 border-b border-gray-400 pb-2 relative">
        <h3 class="m-0 text-lg">{{ displayInfo.name }}</h3>
        <button
          @click="closePanel"
          class="absolute top-0 right-0 translate-x-1/2 translate-y-[-50%] border-none text-white rounded-full cursor-pointer text-sm flex items-center justify-center transition-colors duration-200 box-border"
          style="width: 24px; height: 24px; padding: 0; background-color: transparent;"
          @mouseover="($event) => ($event.target! as any).style.backgroundColor='rgba(85, 185, 181, 0.8)'"
          @mouseleave="($event) => ($event.target! as any).style.backgroundColor='transparent'"
        >
          ✕
        </button>
      </div>

      <div v-if="displayInfo.subdomain" class="flex flex-col gap-2">
        <div
          v-for="section in displayInfo.subdomain"
          :key="section.title"
          class="border border-gray-600 rounded"
        >
          <div
            class="flex justify-between items-center p-2 bg-gray-700 cursor-pointer"
            @click="toggleSection(section.title)"
          >
            <span class="font-bold">{{ section.title }}</span>
            <span>{{ expandedSections[section.title] ? '▲' : '▼' }}</span>
          </div>

          <div
            v-show="expandedSections[section.title] !== false"
            class="p-2"
          >
            <div
              v-for="(value, key) in section"
              :key="key"
              v-show="key !== 'title'"
              class="flex flex-col py-1"
            >
              <div class="flex justify-between">
                <span class="font-bold flex-1">{{ key }}:</span>
                <div class="flex-1 text-right">
                  <input
                    v-if="isEditable(value)"
                    :value="String(getValue(value))"
                    @input="(e) => updateValue(getRefName(value), (e.target as HTMLInputElement).value)"
                    class="bg-gray-600 text-white border border-gray-500 rounded px-1 py-0.5 w-20 text-right"
                    type="number"
                  />
                  <span v-else-if="!isArrayValue(value)">{{ getValue(value) }}</span>
                </div>
              </div>

              <!-- 特殊处理数组值（如坐标和旋转） -->
              <div v-if="isArrayValue(value)" class="ml-4 mt-1">
                <div v-if="(getValue(value) as any[]).length === 3" class="grid grid-cols-3 gap-1">
                  <div class="flex flex-col items-center">
                    <span class="text-xs text-gray-300">X</span>
                    <span>{{ (getValue(value) as any[])[0].toFixed(4) }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <span class="text-xs text-gray-300">Y</span>
                    <span>{{ (getValue(value) as any[])[1].toFixed(4) }}</span>
                  </div>
                  <div class="flex flex-col items-center">
                    <span class="text-xs text-gray-300">Z</span>
                    <span>{{ (getValue(value) as any[])[2].toFixed(4) }}</span>
                  </div>
                </div>
                <div v-else class="text-right">
                  {{ formatArrayValue(getValue(value) as any[]) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="flex flex-col gap-2">
        <div
          v-for="(value, key) in displayInfo"
          :key="key"
          v-show="key !== 'name' && key !== 'subdomain'"
          class="flex flex-col py-1"
        >
          <div class="flex justify-between">
            <span class="font-bold flex-1">{{ key }}:</span>
            <div class="flex-1 text-right">
              <input
                v-if="isEditable(value)"
                :value="String(getValue(value))"
                @input="(e) => updateValue(getRefName(value), (e.target as HTMLInputElement).value)"
                class="bg-gray-600 text-white border border-gray-500 rounded px-1 py-0.5 w-20 text-right"
                type="number"
              />
              <span v-else-if="!isArrayValue(value)">{{ getValue(value) }}</span>
            </div>
          </div>

          <!-- 特殊处理数组值（如坐标和旋转） -->
          <div v-if="isArrayValue(value)" class="ml-4 mt-1">
            <div v-if="(getValue(value) as any[]).length === 3" class="grid grid-cols-3 gap-1">
              <div class="flex flex-col items-center">
                <span class="text-xs text-gray-300">X</span>
                <span>{{ (getValue(value) as any[])[0].toFixed(4) }}</span>
              </div>
              <div class="flex flex-col items-center">
                <span class="text-xs text-gray-300">Y</span>
                <span>{{ (getValue(value) as any[])[1].toFixed(4) }}</span>
              </div>
              <div class="flex flex-col items-center">
                <span class="text-xs text-gray-300">Z</span>
                <span>{{ (getValue(value) as any[])[2].toFixed(4) }}</span>
              </div>
            </div>
            <div v-else class="text-right">
              {{ formatArrayValue(getValue(value) as any[]) }}
            </div>
          </div>
        </div>
      </div>

      <div class="mt-4 text-center border-t border-gray-400 pt-2">
        <slot name="footer"></slot>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 移除了所有原来的样式，使用Tailwind CSS类替代 */
</style>
